<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>服务维护时间设置</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="handleStopService">
              立即停止服务
            </el-button>
          </div>

          <div>
            <el-form label-width="100px">
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="起始时间">
                    <el-date-picker v-model="formData.startTime" type="datetime" placeholder="选择起始时间"
                      value-format="yyyy-MM-dd HH:mm:ss" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="结束时间">
                    <el-date-picker v-model="formData.endTime" type="datetime" placeholder="选择结束时间"
                      value-format="yyyy-MM-dd HH:mm:ss" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <!-- 系统维护 </br>
          <span v-if="formData.startTime !=null || formData.endTime != null">  {{this.formData.startTime}} 到 {{this.formData.endTime}}</span> -->
          </div>
        </el-card>

      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>在线人数</span>
          </div>
          <div class="card-panel">
            <div class="card-panel-num">{{ statistics.onlineUsers || 0 }}</div>
            <div class="card-panel-text">当前在线用户</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>今日新增用户数量</span>
          </div>
          <div class="card-panel">
            <div class="card-panel-num">{{ statistics.todayAddUserCount || 0 }}</div>
            <div class="card-panel-text">今日新增数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>总用户数</span>
          </div>
          <div class="card-panel">
            <div class="card-panel-num">{{ statistics.totalUsers || 0 }}</div>
            <div class="card-panel-text">累计注册用户</div>
          </div>
        </el-card>
      </el-col>

    </el-row>

    <!-- 搜索条件 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-date-picker v-model="createTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-col>
      <el-col :span="12">
        <el-col :span="4">
          <div style="float: left;">
            <el-button type="primary" plain icon="el-icon-search" @click="searchTotal">搜索</el-button>
          </div>
        </el-col>
        <div style="float: right;">
          <el-tooltip class="item" effect="dark" content="设置手续费以及商品信息的全局设置" placement="top">
            <el-button type="info" plain icon="el-icon-setting" @click="globalSettings">全局设置</el-button>
          </el-tooltip>
          <el-button type="success" plain icon="el-icon-download" @click="handleTemplate">一键下载</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 图表展示 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>兑换</span>
          </div>
          <div class="card-panel-count">
            <div class="card-panel-count-text">总次数： <span class="card-panel-count-num">{{
              infoTotalFormData.exchangeRecordFormData.infoTotal || 0 }}</span></div>
            <div class="card-panel-count-text">总卡量： <span class="card-panel-count-num">{{
              infoTotalFormData.exchangeRecordFormData.balanceTotal || 0 }}</span></div>
            <div class="card-panel-count-text">总积分： <span class="card-panel-count-num">{{
              infoTotalFormData.exchangeRecordFormData.cardTotal || 0 }}</span></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>转赠</span>
          </div>
          <div class="card-panel-count">
            <div class="card-panel-count-text">总次数： <span class="card-panel-count-num">{{
              infoTotalFormData.transferRecordFormData.infoTotal || 0 }}</span></div>
            <div class="card-panel-count-text">总卡量： <span class="card-panel-count-num">{{
              infoTotalFormData.transferRecordFormData.cardTotal || 0 }}</span></div>
            <div class="card-panel-count-text">总耗分： <span class="card-panel-count-num">{{
              infoTotalFormData.transferRecordFormData.balanceTotal || 0 }}</span></div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>账单</span>
          </div>
          <div class="card-panel-count">
            <div class="card-panel-count-text">总次数： <span class="card-panel-count-num">{{
              infoTotalFormData.totalBillInfoFormData.infoTotal || 0 }}</span></div>
            <div class="card-panel-count-text">总卡量： <span class="card-panel-count-num">{{
              infoTotalFormData.totalBillInfoFormData.cardTotal || 0 }}</span></div>
            <div class="card-panel-count-text">总积分： <span class="card-panel-count-num">{{
              infoTotalFormData.totalBillInfoFormData.balanceTotal || 0 }}</span></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>信息</span>
          </div>
          <div class="card-panel-count">
            <div class="card-panel-count-text">总卡量： <span class="card-panel-count-num">{{
              infoTotalFormData.userInfoTotalFormData.cardTotal || 0 }}</span></div>
            <div class="card-panel-count-text">总积分： <span class="card-panel-count-num">{{
              infoTotalFormData.userInfoTotalFormData.balanceTotal || 0 }}</span></div>
            <div class="card-panel-count-text">总用户： <span class="card-panel-count-num">{{
              infoTotalFormData.userInfoTotalFormData.infoTotal || 0 }}</span></div>
          </div>
        </el-card>
      </el-col>

      <!-- 冻结（筛选） -->
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>冻结</span>
          </div>
          <div class="card-panel-count">
            <div class="card-panel-count-text">总次数： <span class="card-panel-count-num">{{
              infoTotalFormData.totalFreezeRecord.infoTotal || 0 }}</span></div>
            <div class="card-panel-count-text">总冻分： <span class="card-panel-count-num">{{
              infoTotalFormData.totalFreezeRecord.balanceTotal || 0 }}</span></div>
            <div class="card-panel-count-text">总冻卡： <span class="card-panel-count-num">{{
              infoTotalFormData.totalFreezeRecord.cardTotal || 0 }}</span></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>今日交易记录</span>
          </div>
          <el-table v-loading="loading" :data="todayTransactions">
            <el-table-column label="订单编号" align="center" prop="orderId" />
            <el-table-column label="用户名" align="center" prop="userName" />
            <el-table-column label="交易金额" align="center" prop="totalAmount">
              <template slot-scope="scope">
                ¥{{ scope.row.totalAmount }}
              </template>
            </el-table-column>
            <el-table-column label="交易时间" align="center" prop="createDate">
              <template slot-scope="scope">
                {{ parseTime(scope.row.createDate) }}
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                <el-tag type="success">
                  {{ '成功' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 全局设置对话框 -->
    <el-dialog title="全局设置" :visible.sync="settingsDialogVisible" width="600px" :close-on-click-modal="false"
      :close-on-press-escape="false" @close="handleSettingsDialogClose" custom-class="global-settings-dialog">
      <el-form :model="globalSettingsForm" ref="globalSettingsForm" :rules="rules" label-width="140px" size="small">
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="settings-section">
              <div class="section-title">定时设置</div>
              <el-form-item label="时间设置" prop="updateTime">
                <el-date-picker v-model="globalSettingsForm.updateTime" type="datetime" format="yyyy-MM-dd HH:mm"
                  placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-col>


          <el-col :span="24">
            <div class="settings-section">
              <div class="section-title">手续费设置</div>
              <el-form-item label="单笔转赠手续费" prop="transferFee">
                <el-input-number v-model="globalSettingsForm.transferFee" :precision="2" :step="0.1" :min="0"
                  controls-position="right" style="width: 220px">
                  <template slot="append">元</template>
                </el-input-number>
              </el-form-item>
              <el-form-item label="单张卡手续费" prop="cardFee">
                <el-input-number v-model="globalSettingsForm.cardFee" :precision="2" :step="0.1" :min="0"
                  controls-position="right" style="width: 220px">
                  <template slot="append">元</template>
                </el-input-number>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="24">
            <div class="settings-section">
              <div class="section-title">商品设置</div>
              <el-form-item label="商品价格" prop="productPrice">
                <el-input-number v-model="globalSettingsForm.price" :precision="2" :step="0.1" :min="0"
                  controls-position="right" style="width: 220px">
                  <template slot="append">元</template>
                </el-input-number>
              </el-form-item>
              <el-form-item label="数量/张/张" prop="productQuantity">
                <div class="quantity-input">
                  <el-input-number v-model="globalSettingsForm.total" :min="0" :disabled="hasFloatingQuantity"
                    controls-position="right" style="width: 220px" />
                  <!-- <div class="section-title">浮动设置</div> -->
                  <el-tooltip content="填写此项将在系统当前的数量/张/张进行添加" placement="top">
                    <!-- <el-checkbox 
                      v-model="hasFloatingQuantity" 
                      style="margin-left: 15px"
                      @change="handleFloatingQuantityChange"
                    >
                      使用现有浮动数量
                    </el-checkbox> -->

                    <el-input-number v-model="globalSettingsForm.floatingTotal" :min="0" style="margin-left:15px" />
                  </el-tooltip>
                </div>

              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="settingsDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSettingsSubmit" size="small">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getStatistics,
  getOnlineUsers,
  getTodayTransactions,
  getRegisterTotalUsers,
  createMaintenance,
  selectMaintenanceInfo,
  updateMaintenance,
  getTodayAddUserCount,
  searchTotal,
  getGlobalSettings,
  setGlobalSettings,
  onDownload
} from "@/api/statistics";
import dayjs from 'dayjs';




export default {
  name: "Statistics",
  data() {
    return {
      settingsDialogVisible: false,
      submitLoading: false,
      hasFloatingQuantity: false,
      globalSettingsForm: {
        transferFee: 0,
        cardFee: 0,
        price: 0,
        total: 0,
        shopId: 0,
        floatingTotal: 0,
        updateTime: null
      },
      rules: {
        transferFee: [
          { required: true, message: '请输入单笔转赠手续费', trigger: 'blur' }
        ],
        cardFee: [
          { required: true, message: '请输入单张卡手续费', trigger: 'blur' }
        ],
        ptice: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        total: [
          { required: true, message: '请输入数量/张/张', trigger: 'blur' }
        ]
      },
      loading: false,
      statistics: {
        totalPurchases: 0,
        onlineUsers: 0,
        todayAddUserCount: 0,
        totalUsers: 0
      },
      todayTransactions: [],
      purchaseChart: null,
      rechargeChart: null,
      purchaseTrendData: {
        dates: [],
        values: []
      },
      rechargeData: {
        dates: [],
        values: []
      },
      formData: {
        startTime: null,
        endTime: null,
      },
      statistics: {
        totalPurchases: 42
      },
      infoTotalFormData: {
        userInfoTotalFormData: {
          infoTotal: 0,
          balanceTotal: 0,
          cardTotal: 0
        },
        transferRecordFormData: {
          infoTotal: 0,
          balanceTotal: 0,
          cardTotal: 0
        },
        exchangeRecordFormData: {
          infoTotal: 0,
          balanceTotal: 0,
          cardTotal: 0
        },
        totalBillInfoFormData: {
          infoTotal: 0,
          balanceTotal: 0,
          cardTotal: 0
        },
        totalFreezeRecord: {
          infoTotal: 0,
          balanceTotal: 0,
          cardTotal: 0
        },
      },
      createTime: ''
    }
  },
  mounted() {
    this.getStatisticsData()
    this.getTodayTransactionsList()
    this.getTotalUsers()
    this.getTodayAddUserCount()
    this.getOnlineUsersCount()
    this.getServiceInfo()
    this.searchTotal()
    // 每分钟更新一次在线人数
    this.timer = setInterval(() => {
      this.getOnlineUsersCount()
    }, 60000)

    // 每分钟更新一次在线人数
    this.timer = setInterval(() => {
      this.getStatisticsData()
      this.getTodayTransactionsList()
      this.getTotalUsers()
      this.getTodayAddUserCount()
      this.getOnlineUsersCount()
    }, 30000)

    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', () => {
      this.purchaseChart && this.purchaseChart.resize()
      this.rechargeChart && this.rechargeChart.resize()
    })
    // 监听全局设置更新事件
    // this.$bus.$on('globalSettingsUpdated', this.handleGlobalSettingsUpdate)
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
    if (this.purchaseChart) {
      this.purchaseChart.dispose()
    }
    if (this.rechargeChart) {
      this.rechargeChart.dispose()
    }
    // 移除事件监听
    // this.$bus.$off('globalSettingsUpdated', this.handleGlobalSettingsUpdate)
  },
  methods: {
    // 一键下载
    async handleTemplate() {
      console.log("this.createTime", this.createTime)
      let params = {}
      if (this.createTime && this.createTime.length === 2) {
        params.startTime = this.createTime[0];
        params.endTime = this.createTime[1];
      }
      this.download('system/exchange/export', params, `兑换记录表${new Date().getTime()}.xlsx`);
      this.download('system/freeze/export', params, `冻结记录表${new Date().getTime()}.xlsx`);
      this.download('system/log/export', { type: 0 }, `积分转赠记录表${new Date().getTime()}.xlsx`);
      this.download('system/log/export', { type: 1 }, `会员卡转赠记录表${new Date().getTime()}.xlsx`);
      this.download('bill/billView/export', params, `账单记录表${new Date().getTime()}.xlsx`);
      this.download('userInfo/userInfo/export', params, `用户信息记录表${new Date().getTime()}.xlsx`);
    },
    // 处理全局设置更新
    // async handleGlobalSettingsUpdate() {
    //   // 重新加载当前页面数据
    //   await this.mounted();
    // },
    // 打开全局设置对话框
    async globalSettings() {
      try {
        this.settingsDialogVisible = true;
        // 获取当前的商品信息
        await getGlobalSettings().then(res => {
          if (res.code == 200) {
            this.globalSettingsForm = res.data
          }
        })
      } catch (error) {
        console.error(error);
        this.$modal.msgError('获取设置数据失败');
      }
    },

    // 处理浮动数量复选框变化
    handleFloatingQuantityChange(checked) {
      if (checked) {
        this.globalSettingsForm.productQuantity = 0;
      }
    },

    // 处理设置提交
    async handleSettingsSubmit() {
      this.$refs.globalSettingsForm.validate(async valid => {
        if (!valid) return;

        try {
          this.submitLoading = true;

          console.log("this.globalSettingsForm", this.globalSettingsForm)

          // 构建提交数据
          const res = await setGlobalSettings(this.globalSettingsForm);

          if (res.code === 200) {
            this.$modal.msgSuccess('设置更新成功');
            this.settingsDialogVisible = false;

            // 触发全局事件，通知其他页面更新
            // this.$bus.$emit('globalSettingsUpdated');

            // 重新加载当前页面数据
            await this.getStatisticsData();
          }
        } catch (error) {
          this.$modal.msgError('设置更新失败');
        } finally {
          this.submitLoading = false;
        }
      });
    },

    // 关闭对话框时重置表单
    handleSettingsDialogClose() {
      this.$refs.globalSettingsForm.resetFields();
      this.hasFloatingQuantity = false;
    },
    // 搜索
    async searchTotal() {
      let startTime = "";
      let endTime = ""
      if (this.createTime) {
        startTime = dayjs(this.createTime[0]).format('YYYY-MM-DD HH:mm:ss');
        endTime = dayjs(this.createTime[1]).format('YYYY-MM-DD HH:mm:ss');
      }

      await searchTotal(startTime, endTime).then(res => {
        console.log("res", res)
        this.infoTotalFormData = res.data;
      })
    },
    async getServiceInfo() {
      await selectMaintenanceInfo().then(res => {
        if (res.data) {
          this.formData = res.data
        }
      })
    },
    handleStopService() {
      // 这里添加实际停止服务的逻辑
      this.$confirm('确定要停止服务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用API...
        console.log("this.formData", this.formData)
        if (this.formData) {
          updateMaintenance(this.formData).then(res => {
            if (res.code == 200) {
              this.$message.success('交易服务已暂停!')
            }
          })

        } else {
          createMaintenance({ startTime: this.startTime, endTime: this.endTime }).then(res => {
            if (res.code == 200) {
              this.$message.success('交易服务已暂停!')
            }
          })
        }

      })
    },
    // 获取统计数据
    async getStatisticsData() {
      try {
        const res = await getStatistics()
        console.log('统计数据:', res)
        if (res.code === 200) {
          this.statistics.totalPurchases = res.data
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
        this.$modal.msgError('获取统计数据失败')
      }
    },
    // 获取在线用户数
    async getOnlineUsersCount() {
      try {
        const res = await getOnlineUsers()
        console.log('在线用户数:', res)
        if (res.code === 200) {
          let uniqueArr = Array.from(new Map(res.rows.map(item => [item.userName, item])).values());
          this.statistics = {
            ...this.statistics,
            onlineUsers: uniqueArr.length
          }
        }
      } catch (error) {
        console.error('获取在线用户数失败:', error)
      }
    },
    // 获取总用户数
    async getTotalUsers() {
      try {
        const res = await getRegisterTotalUsers()
        if (res.code === 200) {
          this.statistics = {
            ...this.statistics,
            totalUsers: res.data
          }
        }
      } catch (error) {
        console.error('获取总用户数失败:', error)
      }
    },
    // 获取今日新增用户数量
    async getTodayAddUserCount() {
      try {
        const res = await getTodayAddUserCount()
        if (res.code === 200) {
          this.statistics = {
            ...this.statistics,
            todayAddUserCount: res.data
          }
        }
      } catch (error) {
        console.error('获取今日新增用户数量失败:', error)
        this.$modal.msgError('获取今日新增用户数量失败')
      }
    },
    // 获取今日交易记录
    async getTodayTransactionsList() {
      this.loading = true
      try {
        const res = await getTodayTransactions()
        if (res.code === 200) {
          this.todayTransactions = res.data
        }
      } catch (error) {
        console.error('获取今日交易记录失败:', error)
        this.$modal.msgError('获取今日交易记录失败')
      } finally {
        this.loading = false
      }
    },
    // 获取本月所有日期
    getCurrentMonthDays() {
      const dates = [];
      const values = [];
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth();
      // 获取当月的天数
      const daysInMonth = new Date(year, month + 1, 0).getDate();

      // 生成当月每一天的日期
      for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(year, month, i);
        const formatDate = date.toISOString().split('T')[0]; // 格式：YYYY-MM-DD
        dates.push(formatDate);
        values.push(0); // 初始化值为0
      }
      return { dates, values };
    },

  }
}
</script>

<style scoped>
.readonly-text {
  color: #606266;
  /* line-height: 5px; 与输入框高度对齐 */
  /* padding-left: 15px; 模拟输入框内边距 */
}

.card-panel-text {
  color: #909399;
  font-size: 14px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-date-editor {
  width: 100%;
}


.card-panel {
  text-align: center;
  padding: 20px 0;
}

.card-panel-num {
  font-size: 24px;
  font-weight: bold;
  color: #666;
  margin-bottom: 10px;
}

.card-panel-count-text {
  color: #999;
  font-weight: bold;
  font-size: 14px;
}

.chart-wrapper {
  padding: 10px;
  background-color: #fff;
}

.card-panel-count {
  text-align: left;
  padding: 2px 0;
}

.card-panel-count-num {
  font-size: 24px;
  font-weight: bold;
  color: #666;
  margin-bottom: 10px;
  margin-left: 40px;
}


.global-settings-dialog {
  .settings-section {
    background: #f8f9fa;
    border-radius: 4px;
    padding: 15px 20px;
    margin-bottom: 20px;

    .section-title {
      font-size: 15px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 15px;
      position: relative;
      padding-left: 10px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 3px;
        height: 16px;
        background: #409EFF;
        border-radius: 2px;
      }
    }
  }

  .quantity-input {
    display: flex;
    align-items: center;
  }

  /deep/ .el-input-number {
    .el-input__inner {
      text-align: left;
    }
  }

  /deep/ .el-form-item {
    margin-bottom: 22px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  /deep/ .el-form-item__label {
    font-weight: normal;
    color: #606266;
  }
}
</style>